﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Seagull.FrameInspector.Seagull.DAL
{
    public class FrameReader : IDisposable
    {
        private readonly BinaryReader _reader;

        public FrameReader(Stream inputStream)
        {
            _reader = new BinaryReader(inputStream);
        }

        /// <summary>
        /// 读取并返回帧，直到没有更多的帧。
        /// </summary>
        /// <returns></returns>
        public IEnumerable<DateTime> ReadToEnd()
        {
            DateTime frame;
            while((frame = Read())!=DateTime.MinValue)
            {
                yield return frame;
            }
        }

        /// <summary>
        /// 读取1帧并返回。若已经没有更多的帧则返回<c>null</c>。
        /// </summary>
        /// <returns></returns>
        public DateTime Read()
        {
            if(_reader.BaseStream.Position < _reader.BaseStream.Length)
            {
                _reader.BaseStream.Seek(4, SeekOrigin.Current);
                var reader = _reader;
                var timestamp = TimestampAccessor.Read(reader);

                _reader.BaseStream.Seek(202, SeekOrigin.Current);
                
                _reader.BaseStream.Seek(5, SeekOrigin.Current);
                return timestamp;
            }
            return DateTime.MinValue;
        }

        public void Dispose()
        {
            if(_reader != null)
                _reader.Close();
        }
    }
}